package cn.edu.yzu.scholarship.render;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import com.jfinal.core.JFinal;
import com.jfinal.render.FileRender;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;

public class FileExtendRender extends FileRender {

	private File file;
	private String showName;
	
	public FileExtendRender(String showName,File file) {
		super(file);
		this.file = file;
		this.showName = showName;
	}
	
	public void render() {
		
		if (file == null || !file.isFile() || file.length() > Integer.MAX_VALUE) {
			RenderFactory.me().getErrorRender(404).setContext(request, response).render();
			return ;
        }
		
		try {
			response.addHeader("Content-disposition", "attachment; filename=" + new String(showName.getBytes("GBK"), "ISO8859-1"));
		} catch (UnsupportedEncodingException e) {
			response.addHeader("Content-disposition", "attachment; filename=" + showName);
		}
		
        String contentType = JFinal.me().getServletContext().getMimeType(file.getName());

        response.setContentType(contentType);
        response.setContentLength((int)file.length());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            for (int n; (n = inputStream.read(buffer)) != -1;) {
                outputStream.write(buffer, 0, n);
            }
            outputStream.flush();
        }
        catch (Exception e) {
        	throw new RenderException(e);
        }
        finally {
            if (inputStream != null) {
                try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
            if (outputStream != null) {
            	try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
	}
}